import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

plt.rcParams["font.sans-serif"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]
plt.rcParams["axes.unicode_minus"] = False
class StatsGoals:
    """处理统计与目标管理的类"""

    def __init__(self, app):
        self.app = app
        self.storage = app.storage
        self.colors = app.colors
        self.style = app.style

    def show_stats_view(self):
        """显示心情统计视图"""
        # 清除现有界面
        for widget in self.app.winfo_children():
            widget.destroy()

        # 主框架
        stats_frame = ttk.Frame(self.app, padding=20)
        stats_frame.pack(fill=tk.BOTH, expand=True)

        # 返回按钮
        back_btn = ttk.Button(stats_frame, text="返回", command=self.app.create_main_frame)
        back_btn.pack(anchor="nw", pady=(0, 10))

        # 标题
        title_label = ttk.Label(stats_frame, text="心情统计", style="Subheader.TLabel")
        title_label.pack(pady=(0, 20), anchor="w")

        # 筛选选项
        filter_frame = ttk.Frame(stats_frame)
        filter_frame.pack(fill=tk.X, pady=10)

        ttk.Label(filter_frame, text="统计月份:").grid(row=0, column=0, padx=5, pady=5, sticky="w")
        self.month_var = tk.StringVar()
        month_entry = ttk.Entry(filter_frame, textvariable=self.month_var, width=10)
        month_entry.grid(row=0, column=1, padx=5, pady=5, sticky="w")
        ttk.Label(filter_frame, text="(年-月)").grid(row=0, column=2, padx=5, pady=5, sticky="w")

        # 获取当前年月作为默认值
        now = datetime.now()
        self.month_var.set(now.strftime("%Y-%m"))

        stats_btn = ttk.Button(
            filter_frame,
            text="生成统计",
            command=lambda: self.generate_mood_stats(self.month_var.get())
        )
        stats_btn.grid(row=0, column=3, padx=5, pady=5, sticky="w")

        # 统计结果区域
        self.stats_frame = ttk.Frame(stats_frame)
        self.stats_frame.pack(fill=tk.BOTH, expand=True, pady=20)

        # 初始生成当前月份的统计
        self.generate_mood_stats(now.strftime("%Y-%m"))

    def generate_mood_stats(self, month_str):
        """生成心情统计"""
        # 清除现有统计结果
        for widget in self.stats_frame.winfo_children():
            widget.destroy()

        # 筛选当月日志
        filtered_logs = [log for log in self.app.checkins if log["date"].startswith(month_str)]

        if not filtered_logs:
            ttk.Label(self.stats_frame, text=f"未找到 {month_str} 的打卡记录", font=("Arial", 12)).pack(pady=20)
            return

        # 计算统计数据
        stats = {mood: 0 for mood in self.storage.PRESET_MOODS}
        for log in filtered_logs:
            if log['mood'] in stats:
                stats[log['mood']] += 1

        # 创建图表
        fig = Figure(figsize=(6, 4), dpi=100)
        ax = fig.add_subplot(111)

        # 准备数据
        labels = [f"{self.storage.MOOD_ICONS[i]} {mood}" for i, mood in enumerate(self.storage.PRESET_MOODS)]
        values = [stats[mood] for mood in self.storage.PRESET_MOODS]

        # 绘制柱状图
        bars = ax.bar(labels, values, color=[self.colors["primary"], self.colors["secondary"],
                                             self.colors["accent"], self.colors["neutral"],
                                             self.colors["warning"], self.colors["info"]])

        # 添加数据标签
        for bar in bars:
            height = bar.get_height()
            ax.text(bar.get_x() + bar.get_width() / 2., height,
                    f'{height}', ha='center', va='bottom')

        ax.set_title(f'{month_str} 心情统计')
        ax.set_xlabel('心情')
        ax.set_ylabel('天数')

        # 创建画布并显示图表
        canvas = FigureCanvasTkAgg(fig, master=self.stats_frame)
        canvas.draw()
        canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)

        # 显示统计摘要
        summary_frame = ttk.Frame(self.stats_frame)
        summary_frame.pack(fill=tk.X, pady=10)

        ttk.Label(summary_frame, text=f"当月共有 {len(filtered_logs)} 天打卡记录", font=("Arial", 12)).pack(anchor="w")

        # 找出最常出现的心情
        max_count = max(values)
        most_frequent_moods = [labels[i] for i, v in enumerate(values) if v == max_count]

        ttk.Label(summary_frame, text=f"最常出现的心情: {', '.join(most_frequent_moods)}", font=("Arial", 12)).pack(
            anchor="w")

    def show_goals_view(self):
        """显示学习目标视图"""
        # 清除现有界面
        for widget in self.app.winfo_children():
            widget.destroy()

        # 主框架
        goals_frame = ttk.Frame(self.app, padding=20)
        goals_frame.pack(fill=tk.BOTH, expand=True)

        # 返回按钮
        back_btn = ttk.Button(goals_frame, text="返回", command=self.app.create_main_frame)
        back_btn.pack(anchor="nw", pady=(0, 10))

        # 标题
        title_label = ttk.Label(goals_frame, text="学习目标管理", style="Subheader.TLabel")
        title_label.pack(pady=(0, 20), anchor="w")

        # 按钮框架
        btn_frame = ttk.Frame(goals_frame)
        btn_frame.pack(fill=tk.X, pady=10)

        # 添加目标按钮
        add_btn = ttk.Button(
            btn_frame,
            text="添加新目标",
            command=self.add_new_goal,
            style="TButton"
        )
        self.style.configure("AddGoal.TButton", background=self.colors["accent"])
        add_btn.configure(style="AddGoal.TButton")
        add_btn.pack(side=tk.LEFT, padx=(0, 10))

        # 刷新按钮
        refresh_btn = ttk.Button(
            btn_frame,
            text="刷新",
            command=self.show_goals_view
        )
        refresh_btn.pack(side=tk.LEFT)

        # 目标列表
        self.goals_tree = ttk.Treeview(goals_frame, columns=("id", "description", "status"), show="headings")
        self.goals_tree.heading("id", text="ID")
        self.goals_tree.heading("description", text="目标描述")
        self.goals_tree.heading("status", text="状态")

        self.goals_tree.column("id", width=50, anchor=tk.CENTER)
        self.goals_tree.column("description", width=500)
        self.goals_tree.column("status", width=100, anchor=tk.CENTER)

        self.goals_tree.pack(fill=tk.BOTH, expand=True, pady=10)

        # 绑定双击事件更新目标
        self.goals_tree.bind("<Double-1>", self.update_goal)

        # 右键菜单
        self.goals_tree.bind("<Button-3>", self.show_goal_menu)
        self.menu = tk.Menu(self.app, tearoff=0)
        self.menu.add_command(label="更新状态", command=self.update_goal_from_menu)
        self.menu.add_command(label="删除目标", command=self.delete_goal_from_menu)

        # 显示目标
        self.display_goals()

    def display_goals(self):
        """显示目标列表"""
        # 清空树视图
        for item in self.goals_tree.get_children():
            self.goals_tree.delete(item)

        # 显示目标
        if not self.app.goals:
            self.goals_tree.insert("", tk.END, values=("", "暂无学习目标", ""))
            return

        # 设置状态颜色
        status_colors = {
            "进行中": self.colors["primary"],
            "已完成": self.colors["success"],
            "暂停": self.colors["warning"]
        }

        for goal in self.app.goals:
            item = self.goals_tree.insert(
                "", tk.END,
                values=(goal["goal_id"], goal["description"], goal["status"])
            )

            # 设置状态列的颜色
            if goal["status"] in status_colors:
                self.goals_tree.tag_configure(goal["goal_id"], foreground=status_colors[goal["status"]])
                self.goals_tree.item(item, tags=(goal["goal_id"],))

    def add_new_goal(self):
        """添加新目标"""
        description = simpledialog.askstring("添加新目标", "请输入目标描述:", parent=self.app)

        if not description:
            return

        # 生成目标ID
        goal_id = f"g{len(self.app.goals) + 1}"

        # 创建新目标
        new_goal = {
            "goal_id": goal_id,
            "description": description,
            "status": "进行中"
        }

        # 添加到目标列表
        self.app.goals.append(new_goal)
        self.storage.save_goals_to_file(self.app.goals)

        # 刷新显示
        self.display_goals()

        # 显示成功消息
        messagebox.showinfo("成功", f"已添加新目标: {description}")

    def update_goal(self, event):
        """更新目标"""
        selection = self.goals_tree.selection()
        if not selection:
            return

        item = selection[0]
        goal_id = self.goals_tree.item(item, "values")[0]

        if not goal_id or goal_id == "":
            return

        # 查找目标
        goal = next((g for g in self.app.goals if g["goal_id"] == goal_id), None)
        if not goal:
            return

        # 创建更新窗口
        update_window = tk.Toplevel(self.app)
        update_window.title(f"更新目标 - {goal['description']}")
        update_window.geometry("400x200")
        update_window.resizable(False, False)

        # 框架
        frame = ttk.Frame(update_window, padding=20)
        frame.pack(fill=tk.BOTH, expand=True)

        # 目标描述
        ttk.Label(frame, text="目标描述:").pack(anchor="w", pady=(0, 5))
        desc_var = tk.StringVar(value=goal["description"])
        desc_entry = ttk.Entry(frame, textvariable=desc_var, width=40)
        desc_entry.pack(fill=tk.X, pady=(0, 10))

        # 状态
        ttk.Label(frame, text="目标状态:").pack(anchor="w", pady=(0, 5))
        status_var = tk.StringVar(value=goal["status"])
        status_combo = ttk.Combobox(
            frame,
            textvariable=status_var,
            values=["进行中", "已完成", "暂停"],
            state="readonly"
        )
        status_combo.pack(fill=tk.X, pady=(0, 10))

        # 按钮框架
        btn_frame = ttk.Frame(frame)
        btn_frame.pack(fill=tk.X, pady=10)

        # 保存按钮
        save_btn = ttk.Button(
            btn_frame,
            text="保存",
            command=lambda: self.save_goal_changes(goal_id, desc_var.get(), status_var.get(), update_window)
        )
        save_btn.pack(side=tk.LEFT, padx=(0, 10))

        # 取消按钮
        cancel_btn = ttk.Button(
            btn_frame,
            text="取消",
            command=update_window.destroy
        )
        cancel_btn.pack(side=tk.LEFT)

    def save_goal_changes(self, goal_id, description, status, window):
        """保存目标更改"""
        if not description:
            messagebox.showerror("错误", "目标描述不能为空")
            return

        # 查找目标
        for goal in self.app.goals:
            if goal["goal_id"] == goal_id:
                goal["description"] = description
                goal["status"] = status
                break

        # 保存到文件
        self.storage.save_goals_to_file(self.app.goals)

        # 刷新显示
        self.display_goals()

        # 关闭窗口
        window.destroy()

        # 显示成功消息
        messagebox.showinfo("成功", "目标已更新")

    def show_goal_menu(self, event):
        """显示目标右键菜单"""
        region = self.goals_tree.identify_region(event.x, event.y)
        if region == "cell":
            # 选择点击的项
            item = self.goals_tree.identify_row(event.y)
            self.goals_tree.selection_set(item)
            # 显示菜单
            self.menu.post(event.x_root, event.y_root)

    def update_goal_from_menu(self):
        """从菜单更新目标"""
        selection = self.goals_tree.selection()
        if selection:
            self.update_goal(None)

    def delete_goal_from_menu(self):
        """从菜单删除目标"""
        selection = self.goals_tree.selection()
        if not selection:
            return

        item = selection[0]
        goal_id = self.goals_tree.item(item, "values")[0]

        if not goal_id or goal_id == "":
            return

        # 查找目标
        goal = next((g for g in self.app.goals if g["goal_id"] == goal_id), None)
        if not goal:
            return

        # 确认删除
        confirm = messagebox.askyesno("确认删除", f"确定要删除目标 '{goal['description']}' 吗?")
        if not confirm:
            return

        # 删除目标
        self.app.goals = [g for g in self.app.goals if g["goal_id"] != goal_id]
        self.storage.save_goals_to_file(self.app.goals)

        # 从打卡记录中移除关联
        for log in self.app.checkins:
            if "goal_ids" in log:
                log["goal_ids"] = [g_id for g_id in log["goal_ids"] if g_id != goal_id]

        self.storage.save_all_checkins_to_file(self.app.checkins)

        # 刷新显示
        self.display_goals()

        # 显示成功消息
        messagebox.showinfo("成功", "目标已删除")